﻿using Elio.Controls;
using Elio.Interfaces;
using Elio.Sessions;
using Elio.Sessions.Widgets;
using Google.Protobuf.WellKnownTypes;

namespace Elio.Widgets;

public class WidgetSpinner : Picker, ISessionWidget
{
    private readonly List<string> _items = new();
    public BaseSession? Session { get; set; }
    public void Init(InitOptions options)
    {
        (WidthRequest, HeightRequest) = (options.Width, options.Height);
        this.SetPoint(options.X, options.Y);
    }

    public async Task<bool> OnViewReceive(string name, long sid, long fid, params Any[] argv)
    {
        switch (name)
        {
            case "getPrompt":
                await GetPrompt(sid, fid);
                break;

            case "setPrompt":
                SetPrompt(argv);
                break;

            case "select":
                Select(argv);
                break;

            case "setItems":
                SetItems(argv);
                break;

            case "setOnItemSelectedListener":
                SetOnItemSelectedListener(argv);
                break;

            default:
                return false;
        }
        return true;
    }

    private async Task GetPrompt(long sid, long fid)
    {
        string prompt = Title ?? string.Empty;
        await Session!.SendAction("onGetPrompt", sid, fid, prompt.ToAny());
    }

    private void SetPrompt(params Any[] argv) => Title = argv[0].P2String();

    private void Select(params Any[] argv) => SelectedIndex = argv[0].P2Int();

    private void SetItems(params Any[] argv)
    {
        _items.Clear();
        argv
            .ToList()
            .ForEach(i => _items.Add(i.P2String()));
        ItemsSource = _items;
    }

    private void SetOnItemSelectedListener(params Any[] argv)
    {
        async void IndexChanged(object? sender, EventArgs e)
        {
            int index = (sender as WidgetSpinner)!.SelectedIndex;
            await Session!.SendCallback(argv[0].P2Interaction(), null, index.ToAny());
        }
        SelectedIndexChanged += IndexChanged;
    }

}
